﻿using Corina.Common;
using Corina.DataContext.Service;
using Corina.Datamodel.DataObject;
using Corina.Datamodel.Entities;
using Corina.Enumerations;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Net;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;

namespace Corina.DataContext.Master
{
    public class DeviceMessageMaster : MasterBase
    {
        public ResultInfo GetAllItems(string account, string password, string deviceSn, int kindId, string key, bool searchAll, int index, int size)
        {
            ResultValue resultValue = VerifyAccount<ManagerInfo>(account, password);

            ResultInfo result = new ResultInfo(resultValue);

            if (resultValue == ResultValue.Succeed)
            {
                int count = 0;
                var table = GetInstance<DeviceMessageService>().GetAllItems(ConnectionString(DatabaseKeys.CORINA_DATA), deviceSn, kindId, key, searchAll, index, size, ref count);
                string[] columns = table.Columns.OfType<DataColumn>().Select(t => t.ColumnName).ToArray();

                var items = (from t in table.AsEnumerable()
                             select new DataObjectInfo()
                             {
                                 Values = GetObjectOfValue(t, columns)
                             });

                result.DataObjects.AddRange(items);
                result.TotalCount = count;
            }

            return result;
        }

        public ResultInfo Insert(DeviceMessageInfo entity)
        {
            bool flag = GetInstance<DeviceMessageService>().Update(ConnectionString(DatabaseKeys.CORINA_DATA), entity, EntityOperation.Insert);
            return new ResultInfo(flag ? ResultValue.Succeed : ResultValue.Failed);
        }

        public ResultInfo Remove(string account,string password,int id)
        {
            ResultValue resultValue = VerifyAccount<ManagerInfo>(account, password);
            if(resultValue == ResultValue.Succeed)
            {
                bool flag = GetInstance<DeviceMessageService>().Update(ConnectionString(DatabaseKeys.CORINA_DATA), new DeviceMessageInfo() { Id = id }, EntityOperation.Delete);
                if(!flag)
                {
                    resultValue = ResultValue.Failed;
                }
            }

            return new ResultInfo(resultValue);
        }

        public ResultInfo Resolve(string account, string password, int id)
        {
            //DeviceMessageInfo message = GetInstance<DeviceMessageService>().GetEntity(ConnectionString(DatabaseKeys.CORINA_DATA), id);
            //ResultValue resultValue = message.IsAnalysed ? ResultValue.Failed : ResultValue.Succeed;
            //return new ResultInfo(resultValue);
            ResultValue resultValue = VerifyAccount<ManagerInfo>(account, password);
            if (resultValue == ResultValue.Succeed)
            {
                bool flag = GetInstance<DeviceMessageService>().Resolve(ConnectionString(DatabaseKeys.CORINA_DATA), id);
                if (!flag)
                {
                    resultValue = ResultValue.Failed;
                }
                else
                {
                    Task<bool> task = new Task<bool>(() => {
                        return SendNotification(id);
                    });
                    task.Start();
                }
            }

            return new ResultInfo(resultValue);
        }

        public ResultInfo GetEntity(string account, string password, int id)
        {
            ResultValue resultValue = VerifyAccount<ManagerInfo>(account, password);

            ResultInfo result = new ResultInfo(resultValue);

            if (resultValue == ResultValue.Succeed)
            {
                var item = GetInstance<DeviceMessageService>().GetEntity(ConnectionString(DatabaseKeys.CORINA_DATA), id);
                result.Entities.Add(item);
            }

            return result;
        }

        public ResultInfo Insert(string account, string password, string deviceSn, string content, string ipOrMobile)
        {
            ResultValue resultValue = VerifyAccount<ManagerInfo>(account, password);

            if (resultValue == ResultValue.Succeed)
            {
                bool auto_resolve = GetInstance<AutoResolveService>().CheckFlag(ConnectionString(DatabaseKeys.CORINA_PROD), deviceSn);
                
                List<string> items = RegexHelper.MatchMeasure(content);
                if (items.Count > 0)
                {
                    List<DeviceMessageInfo> device_messages = new List<DeviceMessageInfo>();
                    items.ForEach((t) =>
                    {
                        DeviceMessageInfo device_msg = new DeviceMessageInfo()
                        {
                            DeviceSn = deviceSn,
                            Content = t.Remove(0, 7),
                            ProofValue = Regex.Match(t.Substring(t.Length - 5, 4), "[0-9]{1,4}").Value.PadRight(4, '0'),
                            MobileOrIP = ipOrMobile,
                            TransType = TransTypeValue.TCP,
                        };
                        string date = Regex.Match(t, "[0-9]{4}-[0-9]{2}-[0-9]{2}").Value;
                        string time = Regex.Match(t,"[0-9]{2}:[0-9]{2}").Value;
                        int index = device_msg.Content.IndexOf(time);
                        string _content = device_msg.Content.Substring(0, index) + time;

                        device_msg.Md5Code = Utilities.SecurityHelper.GetMd5(_content);

                        device_msg.MeasureTime = Convert.ToDateTime(string.Format("{0} {1}:00", date, time));

                        device_messages.Add(device_msg);
                    });

                    bool flag = GetInstance<DeviceMessageService>().Insert(ConnectionString(DatabaseKeys.CORINA_DATA), device_messages, auto_resolve);
                    if(!flag)
                    {
                        resultValue = ResultValue.Failed;
                    }
                }

            }

            return new ResultInfo(resultValue);
        }

        private bool SendNotification(int messageId)
        {
            var items = GetInstance<MeasureNotificationConfigurationService>().GetNitifyConfig(ConnectionString(DatabaseKeys.CORINA_ACCO), messageId);
            if(items.Count>0)
            {
                MessageSendInfo entity = new MessageSendInfo() { Content = "有新的测试数据提交！", SendWay = items.FirstOrDefault().DestType, UserId = items.FirstOrDefault().UserId };
                return GetInstance<MessageSendService>().Insert(ConnectionString(DatabaseKeys.CORINA_DATA), entity, items.Select(t => t.Dest).ToArray());
            }
            else
            {
                return false;
            }
        }
    }
}
